package com.fly.rest;

import java.util.Arrays;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

/**
 * 
 * RestTemplateTest
 * 
 * @author 00fly
 * @version [版本号, 2018年11月6日]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
@RunWith(SpringRunner.class)
@ContextConfiguration({"/applicationContext.xml"})
public class RestTemplateTest2
{
    private static final Logger LOGGER = LoggerFactory.getLogger(RestTemplateTest2.class);
    
    @Autowired
    private RestTemplate restTemplate;
    
    @Test
    public void testPOST()
    {
        // POST请求只能用MultiValueMap
        String url = "http://127.0.0.1:8080/post";
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
        
        MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
        String path = RestTemplateTest2.class.getResource("/123.jpg").getPath();
        FileSystemResource file = new FileSystemResource(path);
        params.add("file", file);
        params.add("name", "girl");
        params.add("age", "18");
        HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(params, headers);
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, requestEntity, String.class);
        LOGGER.info("ResponseEntity={}", responseEntity);
    }
}
